package com.lbloca.locate.utils;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import androidx.annotation.NonNull;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.lbloca.locate.beans.Pay_message;
import com.lbloca.locate.biz.Config;
import com.lbloca.locate.ui.activity.MainActivity;
import com.lbloca.locate.ui.activity.ServiceActivity;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import okhttp3.Call;

public class PayFailureVerification {

    private Activity activity;

    public PayFailureVerification(Activity activity) {
        this.activity = activity;
        init();
    }

    private void init() {
        new MaterialDialog.Builder(activity)
                .title("支付结果").content("是否已完成付款？")
                .positiveText("已付款").negativeText("未付款")
                .cancelable(false).canceledOnTouchOutside(false)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        queryDialog();
                        dialog.dismiss();
                    }
                })
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                    }
                })
                .show();
    }

    private MaterialDialog mQueryDialog;
    private int TIMETOTAL = 0;

    private void queryDialog() {
        if (activity != null && !activity.isFinishing()) {
            mQueryDialog = new MaterialDialog.Builder(activity)
                    .title("支付结果").content("正在查询订单结果，请您耐心稍等片刻...")
                    .progress(false, 100).positiveText("未付款")
                    .cancelable(false).canceledOnTouchOutside(false)
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            dialog.dismiss();
                            TIMETOTAL = 0;
                            if (mHandler != null && runnable != null) {
                                mHandler.removeCallbacks(runnable);
                                mHandler = null;
                                runnable = null;
                            }
                            activity = null;
                        }
                    })
                    .show();
            mHandler.post(runnable);
        }
    }


    private Runnable runnable = new Runnable() {

        @Override
        public void run() {
            try {
                TIMETOTAL++;
                if (mHandler != null) {
                    mHandler.postDelayed(this, 1000);
                    mHandler.sendEmptyMessage(TIMETOTAL);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    @SuppressWarnings("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int time = msg.what;

            if (mQueryDialog != null) {
                mQueryDialog.setProgress(time);
            }
            if (time % 10 == 0) {
                queryOrder();
            }
            if (time == 100) {
                TIMETOTAL = 0;
                if (mHandler != null && runnable != null) {
                    mHandler.removeCallbacks(runnable);
                    mHandler = null;
                    runnable = null;
                }
                dismissDialog();
                payResultDialog("经过查询您的上笔订单已付款，请问您对此订单是否有疑问？");
            }
        }
    };

    private void queryOrder() {
        String orderNo = SPUtils.getInstance().getString(Config.SPF_KEY_ORDER_NO, "");
        if (!TextUtils.isEmpty(orderNo)) {
            String queryUrl = Config.WX_PAY_QUERY_URL + orderNo;
            OkHttpUtils.get().url(queryUrl)
                    .tag(this).build().execute(new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {

                }

                @Override
                public void onResponse(String response, int id) {
                    if (!TextUtils.isEmpty(response)) {
                        Pay_message payMessage = GsonUtil.json2Bean(response, Pay_message.class);
                        if (payMessage != null) {
                            int status = payMessage.getStatus();
                            if (status == 1) {
                                SPUtils.getInstance().put(Config.SPF_VIP_STATE, 1);
                                dismissDialog();
                                Intent intent =  new Intent(activity, MainActivity.class);
                                intent.putExtra("tabindex", 0);
                                activity.startActivity(intent);
                            }
                        }
                    }
                }
            });
        }
    }

    private void payResultDialog(String content) {
        if (activity != null && !activity.isFinishing()) {
            new MaterialDialog.Builder(activity)
                    .title("支付结果").content(content)
                    .positiveText("没有问题").negativeText("联系客服")
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            dialog.dismiss();
                        }
                    })
                    .onNegative(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            ServiceActivity.start(activity);
                            dialog.dismiss();
                        }
                    })
                    .show();
        }
    }

    private void dismissDialog() {
        if (mQueryDialog != null) {
            mQueryDialog.dismiss();
            mQueryDialog = null;
        }
        runnable = null;
        mHandler = null;
        activity = null;
    }
}
